var pageSize = 22;
var startIndex = 0;
var infoStartIndex = 0;
var infoPageSize = 18;

var searchDs;
var searchKeyWordField;
var vodTypeCombo;
var main_Panel;
var today = new Date();

var itemDs;
var itemGrid;
var infoNameField;
var infoDs;

var itemStatusArray = new Array();
var ItemRecord = Ext.data.Record.create([ {
	name : 'id',
	type : 'String'
}, {
	name : 'itemName',
	type : 'String'
}, {
	name : 'contentFlag',
	type : 'String'
}, {
	name : 'itemOrder',
	type : 'String'
}, {
	name : 'contentVersion',
	type : 'String'
}, {
	name : 'itemDescription',
	type : 'String'
} ]);

var ItemStatusRecord = Ext.data.Record.create([ {
	name : 'type',
	type : 'String'
}, {
	name : 'record',
	type : 'ItemRecord'
} ]);

function getSearchForm() {
	var addNewHeader = new Ext.Button({
		id : "addNewHeaderBtn",
		text : '添加',
		type : "button",
		cls : 'x-toolbar',
		handler : addNewInfoHeader
	});

	var store = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ 'movie', '电影' ], [ 'series', '电视剧' ] ]
	});

	vodTypeCombo = new Ext.form.ComboBox({
		id : 'vodTypeCombo',
		store : store,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 60,
		fieldLabel : '剧头类型',
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	vodTypeCombo.on('select', function(combo, record) {
		loadData();
	});

	// sets default value
	var firstValue = store.getRange()[0].data.value;
	vodTypeCombo.setValue(firstValue);

	searchKeyWordField = new Ext.form.TextField({
		fieldLabel : TXT_search_keyword_label,
		id : 'keyword',
		name : 'keyword',
		allowBlank : true,
		afterRender : function() {
			searchKeyWordField.getEl().on('keyup', function(e) {
				e.stopEvent();
				if ((e.getKey() == Ext.EventObject.ENTER)) {
					searchButtonClick();
				}
			})
		}
	});

	var searchButton = new Ext.Button({
		id : "searchButton",
		text : TXT_search_button_text,
		type : "button",
		cls : 'x-toolbar',
		handler : searchButtonClick
	});

	var searchForm = new Ext.FormPanel({
		frame : true,
		layout : 'column',
		labelAlign : 'right',
		buttonAlign : 'left',
		labelWidth : 60,
		border : false,
		region : 'north',
		height : 60,
		tbar : [
				"-",
				"<span style='font-weight:bold;font-size:11px'>" + TXT_vod_bind
						+ "</span>", '->' ],
		style : 'text-align:right;',
		items : [ {
			layout : 'form',
			width : 50,
			style : 'margin:4px 0 0 0;',
			buttonAlign : 'left',
			labelWidth : 0,
			items : [ addNewHeader ]
		}, {
			columnWidth : .99,
			html : "&nbsp;"
		}, {
			width : 160,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ vodTypeCombo ]
		}, {
			layout : 'form',
			width : 200,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ searchKeyWordField ]
		}, {
			layout : 'form',
			width : 50,
			style : 'margin:4px 0 0 0;',
			buttonAlign : 'left',
			items : [ searchButton ]
		} ]
	});

	return searchForm;
}

function getSearchGrid() {
	var searchSm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});
	var searchCm = new Ext.grid.ColumnModel(
			[
					new Ext.grid.RowNumberer(),
					{
						header : TXT_vod_name,
						dataIndex : 'name',
						width : 290,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : TXT_vod_type,
						dataIndex : 'bizType',
						width : 100,
						fixed : true,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '状态',
						dataIndex : 'status',
						width : 100,
						fixed : true,
						renderer : function(v) {
							if (v == 1) {
								return "<div ext:qtip='有效'>有效</div>";
							} else {
								return "<div ext:qtip='无效'>无效</div>";
							}
						}
					},
					{
						header : 'Code',
						dataIndex : 'code',
						width : 230,
						fixed : true,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '导演',
						dataIndex : 'writeDisplay',
						width : 140,
						fixed : true,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '演员',
						dataIndex : 'actorDisplay',
						width : 140,
						fixed : true,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Operation + '</div>',
						dataIndex : 'index',
						width : 260,
						fixed : true,
						renderer : function(v) {
							var index = v % pageSize;
							var record = searchDs.getAt(index);
							var status = record.get("status");
							var header = "<div width='100%' style='text-align:center'>";
							var editBtn = "<a style='color:blue;text-decoration:underline;cursor:pointer' onClick=editInfoHeader('"
									+ index + "')>" + TXT_common_Edit + "</a>";

							var upStatusBtn = "";
							if (status == 1) {
								upStatusBtn = "<a style='color:blue;text-decoration:underline;cursor:pointer' onClick=updateInfoHeaderStatus('"
										+ index
										+ "')>"
										+ TXT_common_offline
										+ "</a>/";
								upStatusBtn += "<a style='color:blue;text-decoration:underline' disabled='disabled'>"
										+ TXT_common_online + "</a>";
							} else {
								upStatusBtn = "<a style='color:blue;text-decoration:underline' disabled='disabled'>"
										+ TXT_common_offline + "</a>/";
								upStatusBtn += "<a style='color:blue;text-decoration:underline;cursor:pointer' onClick=updateInfoHeaderStatus('"
										+ index
										+ "')>"
										+ TXT_common_online
										+ "</a>";
							}

							return header + editBtn
									+ "&nbsp;&nbsp;&nbsp;&nbsp;" + upStatusBtn
									+ "</div>";
						}
					} ]);

	searchDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			totalProperty : 'totalCount',
			id : 'id',
			fields : [ {
				name : 'name'
			}, {
				name : 'bizType'
			}, {
				name : 'code'
			}, {
				name : 'writeDisplay'
			}, {
				name : 'actorDisplay'
			}, {
				name : 'status'
			}, {
				name : 'index'
			} ]
		})
	});

	searchDs.baseParams = {
		'cmd' : 'infoHeaderCommand',
		'action' : 'getInfoHeaderByName'
	};

	// load data
	loadData();

	var searchGrid = new Ext.grid.GridPanel(
			{
				border : false,
				region : 'center',
				ds : searchDs,
				cm : searchCm,
				sm : searchSm,
				stripeRows : true,
				loadMask : {
					msg : 'searching...'
				},
				viewConfig : {
					forceFit : true
				},
				listeners : {
					'keydown' : function(e) {
						e.stopEvent();
						PagingToolbar_KeyEvent(Ext
								.getCmp('searchGridPagingToolbar'), e);
					}
				},
				bbar : new Ext.PagingToolbar(
						{
							id : 'searchGridPagingToolbar',
							pageSize : pageSize,
							height : 20,
							store : searchDs,
							displayInfo : true,
							displayMsg : TXT_common_paging,
							emptyMsg : TXT_common_no,
							onPagingKeydown : function(e) {
								PagingToolbar_KeyEvent(this, e);
							},
							onClick : function(which) {
								switch (which) {
								case 'prev':
									startIndex = startIndex - pageSize;
									break;
								case 'first':
									startIndex = 0;
									break;
								case 'next':
									startIndex = startIndex + pageSize;
									break;
								case 'last':
									startIndex = ((this.store.getTotalCount() / pageSize) | 0)
											* pageSize;
									break;
								default:
								}

								// Gets data
								loadData();
							}
						})
			});

	return searchGrid;
}

function PagingToolbar_KeyEvent(thisPagingToolbar, e) {
	if ((e.getKey() == Ext.EventObject.ENTER)) {
		var currPage = thisPagingToolbar.readPage();
		var totalPage = thisPagingToolbar.getPageData().pages;

		if (currPage > totalPage) {
			Ext.Msg.alert(TXT_common_hint, TXT_Common_Correct_PageNum);
			return;
		} else {
			if (currPage <= 0) {
				startIndex = 0;
			} else {
				startIndex = (currPage - 1) * pageSize;
			}

			// Gets data
			loadData();
		}
	}
	return;
}

function displaySearchPanel() {
	Ext.QuickTips.init();
	var searchForm = getSearchForm();
	var searchGrid = getSearchGrid();
	main_Panel = new Ext.Panel({
		border : false,
		region : 'center',
		layout : 'border',
		margins : '5 5 5 5',
		cmargins : '5 5 5 5',
		items : [ searchForm, searchGrid ]
	});

	BestvSearch.glb_mainPanel.add(main_Panel);
	BestvSearch.drawMainFrame(TXT_app_name + ' - ' + TXT_search_title, null);
}

Ext.onReady(displaySearchPanel);

function searchButtonClick() {
	startIndex = 0;

	// Gets data
	loadData();
}

function loadData() {
	var keyWord = searchKeyWordField.getValue();
	if (keyWord) {
		keyWord = keyWord.trim();
	}
	var headerType = vodTypeCombo.getValue();

	searchDs
			.load({
				params : {
					keyword : keyWord,
					headerType : headerType,
					start : startIndex,
					limit : pageSize,
					ulf : 'y',
					dataSourceKey : BestvSearch.DataSourceKey
				},
				callback : function(r, options, success) {
					if (r.length == 0 && !success) {
						if (searchDs.reader.responseText == '[null]') {
							Ext.Msg
									.alert(
											TXT_common_hint,
											TXT_common_relogin,
											function() {
												window.location.href = '../eni/common/logout.jsp';
											});
							return;
						} else {
							Ext.Msg.alert(TXT_common_hint,
									TXT_SITE_CONFIGURATION_CHECK);
							return;
						}
					}
				}
			});
}

function addNewInfoHeader() {
	getInfoHeaderForm(true, '');
}

function editInfoHeader(index) {
	var record = searchDs.getAt(index);
	var code = record.get("code");

	getInfoHeaderForm(false, code)
}

function updateInfoHeaderStatus(index) {
	var record = searchDs.getAt(index);
	var code = record.get("code");
	var status = record.get("status");
	var name = record.get("name");

	var confir_msg = "";
	var toStatus = 0;
	if (status == 1) {
		confir_msg = '你确定要对以下剧头进行下线操作吗？'
		toStatus = 0;
	} else {
		confir_msg = '你确定要对以下剧头进行上线操作吗？'
		toStatus = 1;
	}
	Ext.Msg
			.confirm(
					TXT_common_hint,
					confir_msg + "<br>" + TXT_vod_name + ":" + name
							+ "<br>Code: " + code,
					function(btn) {
						if (btn == 'yes') {
							var url = DISPATCH_URL
									+ "?cmd=infoHeaderCommand&action=updateInfoHeaderStatus&ulf=y&code="
									+ code + "&status=" + toStatus
									+ "&dataSourceKey="
									+ BestvSearch.DataSourceKey + "&flag="
									+ Math.random();

							var conn = Ext.lib.Ajax.getConnectionObject().conn;

							conn.open("GET", url, false);
							conn.send(null);
							if (conn.responseText == 'success') {
								Ext.Msg.alert(TXT_common_hint,
										TXT_Common_Operation_Success);
								loadData();
							} else {
								Ext.Msg.alert(TXT_common_hint,
										TXT_common_access_fail);
							}
						}
					});
}

function getInfoHeaderForm(isNew, code) {
	var header = null;
	var headerId = '0';
	if (!isNew) {
		header = getHeaderDetail(code);
		if (header != null && header.length > 0) {
			headerId = header[0].id;
		}
	}

	var headerItemGrid = getHeaderItemsGrid(isNew, headerId);
	var headerName = new Ext.form.TextField({
		fieldLabel : '<b style="color:red;">* </b> 名&nbsp;&nbsp;&nbsp;&nbsp;称',
		id : 'headerName',
		name : 'headerName',
		allowBlank : false
	});
	if (!isNew) {
		headerName.setValue(header[0].name);
	}

	var headerAliasName = new Ext.form.TextField({
		fieldLabel : '别&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名',
		id : 'headerAliasName',
		name : 'headerAliasName',
		allowBlank : true
	});
	if (!isNew) {
		headerAliasName.setValue(header[0].aliasName);
	}

	var headerTypeStore = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ 'movie', '电影' ], [ 'series', '电视剧' ] ]
	});

	var headerTypeCombo = new Ext.form.ComboBox({
		id : 'headerType',
		store : headerTypeStore,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 60,
		fieldLabel : '剧头类型',
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	// sets default value
	if (isNew) {
		var firstValue = headerTypeStore.getRange()[0].data.value;
		headerTypeCombo.setValue(firstValue);
	} else {
		headerTypeCombo.setValue(header[0].headerType);
	}

	var headerGenre = new Ext.form.TextField({
		fieldLabel : '流&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;派',
		id : 'headerGenre',
		name : 'headerGenre',
		emptyText : TXT_Common_Space_Split,
		allowBlank : true
	});
	if (!isNew) {
		headerGenre.setValue(header[0].genre);
	}

	var headerTags = new Ext.form.TextField({
		fieldLabel : '标&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;签',
		id : 'headerTags',
		name : 'headerTags',
		emptyText : TXT_Common_Space_Split,
		allowBlank : true
	});
	if (!isNew) {
		headerTags.setValue(header[0].tags);
	}

	var headerWriters = new Ext.form.TextField({
		fieldLabel : '导&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;演',
		id : 'headerWriters',
		name : 'headerWriters',
		emptyText : TXT_Common_Space_Split,
		allowBlank : true
	});
	if (!isNew) {
		headerWriters.setValue(header[0].writers);
	}

	var headerActors = new Ext.form.TextField({
		fieldLabel : '演&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;员',
		id : 'headerActors',
		name : 'headerActors',
		emptyText : TXT_Common_Space_Split,
		allowBlank : true
	});
	if (!isNew) {
		headerActors.setValue(header[0].actors);
	}

	var headerRegion = new Ext.form.TextField({
		fieldLabel : '地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;区',
		id : 'headerRegion',
		name : 'headerRegion',
		emptyText : TXT_Common_Space_Split,
		allowBlank : true
	});
	if (!isNew) {
		headerRegion.setValue(header[0].region);
	}

	var headerReleased = new Ext.form.DateField({
		fieldLabel : '上映时间',
		id : 'headerReleased',
		name : 'headerReleased',
		allowBlank : true,
		format : "Y-m-d",
		width : 130,
		value : today.format('Y-m-d')
	});
	if (!isNew) {
		headerReleased.setValue(header[0].released);
	}

	var headerVodType = getBizTypeComBox();
	if (!isNew) {
		headerVodType.setValue(header[0].p_type);
	}

	var headerDescription = new Ext.form.TextArea({
		fieldLabel : '描&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;述',
		id : 'headerDescription',
		name : 'headerDescription',
		hegith : 100,
		width : 890,
		allowBlank : true
	});
	if (!isNew) {
		headerDescription.setValue(header[0].description);
	}

	var headerClarityStore = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '1', '标清' ], [ '2', '高清' ], [ '3', '高标清' ] ]
	});

	var headerClarityCombo = new Ext.form.ComboBox({
		id : 'headerClarity',
		name : 'headerClarity',
		store : headerClarityStore,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 60,
		fieldLabel : '清&nbsp;晰&nbsp;度',
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	// sets default value
	if (isNew) {
		firstValue = headerClarityStore.getRange()[0].data.value;
		headerClarityCombo.setValue(firstValue);
	} else {
		headerClarityCombo.setValue(header[0].clarityFlag);
	}

	var headerIsChargeStore = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '0', '否' ], [ '1', '是' ] ]
	});

	var headerIsChargeCombo = new Ext.form.ComboBox({
		id : 'headerIsCharge',
		name : 'headerIsCharge',
		store : headerIsChargeStore,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 60,
		fieldLabel : '是否付费',
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	// sets default value
	if (isNew) {
		firstValue = headerIsChargeStore.getRange()[0].data.value;
		headerIsChargeCombo.setValue(firstValue);
	} else {
		headerIsChargeCombo.setValue(header[0].isCharge);
	}

	var headerLanguage = new Ext.form.TextField({
		fieldLabel : '语&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;言',
		id : 'headerLanguage',
		emptyText : TXT_Common_Space_Split,
		name : 'headerLanguage',
		allowBlank : true
	});
	if (!isNew) {
		headerLanguage.setValue(header[0].language);
	}

	var headerCategory = new Ext.form.TextField({
		fieldLabel : '栏&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;目',
		id : 'headerCategory',
		emptyText : TXT_Common_Space_Split,
		name : 'headerCategory',
		allowBlank : true
	});
	if (!isNew) {
		headerCategory.setValue(header[0].category);
	}

	var headerCrowd = new Ext.form.TextField({
		fieldLabel : '面向人群',
		id : 'headerCrowd',
		name : 'headerCrowd',
		allowBlank : true
	});
	if (!isNew) {
		headerCrowd.setValue(header[0].crowd);
	}

	var headerKeyword = new Ext.form.TextField({
		fieldLabel : '关&nbsp;键&nbsp;字',
		id : 'headerKeyword',
		name : 'headerKeyword',
		allowBlank : true
	});
	if (!isNew) {
		headerKeyword.setValue(header[0].keyword);
	}

	var form = new Ext.form.FormPanel({
		labelAlign : 'right',
		title : '',
		labelWidth : 60,
		height : 500,
		autoScroll : true,
		frame : false,
		layout : 'table',
		border : false,
		bodyBorder : false,
		hideBorders : true,
		layoutConfig : {
			columns : 4
		},
		items : [ {
			html : '&nbsp;<br>',
			colspan : 4

		}, {
			layout : 'form',
			width : 250,
			labelAlign : 'right',
			items : headerName
		}, {
			layout : 'form',
			width : 250,
			labelAlign : 'right',
			items : headerAliasName
		}, {
			layout : 'form',
			width : 250,
			labelAlign : 'right',
			items : headerGenre
		}, {
			layout : 'form',
			width : 250,
			labelAlign : 'right',
			items : headerTypeCombo
		}, {
			html : '&nbsp;<br>',
			colspan : 4
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerTags
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerRegion
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerKeyword
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerVodType
		}, {
			html : '&nbsp;<br>',
			colspan : 4
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerReleased
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerWriters
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerActors
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerClarityCombo
		}, {
			html : '&nbsp;<br>',
			colspan : 4
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerLanguage
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerCategory
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerCrowd
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerIsChargeCombo
		}, {
			html : '&nbsp;<br>',
			colspan : 4
		}, {
			layout : 'form',
			labelAlign : 'right',
			items : headerDescription,
			colspan : 4
		}, {
			colspan : 4,
			items : headerItemGrid
		} ]
	});

	showWindow(form, '添加/修改剧头', isNew, headerId, headerName, headerAliasName,
			headerTypeCombo, headerGenre, headerTags, headerWriters,
			headerActors, headerRegion, headerReleased, headerVodType,
			headerDescription, headerClarityCombo, headerIsChargeCombo,
			headerLanguage, headerCategory, headerCrowd, headerKeyword);
}

function showWindow(gridPanel, title, isNew, headerId, headerName,
		headerAliasName, headerTypeCombo, headerGenre, headerTags,
		headerWriters, headerActors, headerRegion, headerReleased,
		headerVodType, headerDescription, headerClarityCombo,
		headerIsChargeCombo, headerLanguage, headerCategory, headerCrowd,
		headerKeyword) {
	var window = null;
	window = new Ext.Window({
		width : 1020,
		autoHeight : true,
		items : gridPanel,
		plain : true,
		title : title,
		autoScroll : true,
		buttons : [
				{
					text : TXT_common_close,
					handler : function() {
						if (window != null) {
							window.close();
						}
					}
				},
				{
					text : TXT_Common_add_item,
					handler : function() {
						addItemToGrid();
					}
				},
				{
					text : TXT_common_save,
					handler : function() {
						saveAll(isNew, headerId, headerName, headerAliasName,
								headerTypeCombo, headerGenre, headerTags,
								headerWriters, headerActors, headerRegion,
								headerReleased, headerVodType,
								headerDescription, headerClarityCombo,
								headerIsChargeCombo, headerLanguage,
								headerCategory, headerCrowd, headerKeyword);
					}
				} ]
	});

	window.setPosition(100, 10);
	window.show();
}

function getBizTypeComBox() {
	var bizTypeDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.JsonReader({
			root : 'p_types',
			id : 'id',
			fields : [ {
				name : 'id'
			}, {
				name : 'name'
			} ]
		})
	});

	bizTypeDs.baseParams = {
		cmd : 'bizType',
		action : 'findBizTypes'
	};

	bizTypeDs.load({
		params : {
			dataSourceKey : BestvSearch.DataSourceKey
		}
	});

	var bizTypeCombo = new Ext.form.ComboBox({
		name : 'bizTypes',
		mode : 'local',
		forceSelection : true,
		displayField : 'name',
		valueField : 'name',
		width : 60,
		triggerAction : 'all',
		selectOnFocus : true,
		triggerClass : 'x-form-trigger2',
		store : bizTypeDs,
		lazyInit : false,
		fieldLabel : '节目类型',
		editable : false
	});

	// sets default value
	bizTypeCombo.setValue('电影');

	return bizTypeCombo;
}

function getHeaderItemsGrid(isNew, headerId) {

	var contentFlagStore = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '1', '正片' ], [ '2', '预告片' ] ]
	});

	var contentFlagCombo = new Ext.form.ComboBox({
		id : 'contentFlagCombo',
		store : contentFlagStore,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 0,
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	var contentVersionStore = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '原声版', '原声版' ], [ '国语版', '国语版' ], [ '粤语版', '粤语版' ],
				[ '自定义', '自定义' ] ]
	});

	var contentVersionCombo = new Ext.form.ComboBox({
		id : 'contentVersionCombo',
		store : contentVersionStore,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 0,
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	var itemSm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});
	var itemCm = new Ext.grid.ColumnModel(
			[
					new Ext.grid.RowNumberer(),
					{
						header : '&nbsp;&nbsp;&nbsp;&nbsp;' + TXT_vod_name,
						dataIndex : 'itemName',
						width : 200,
						renderer : function(v) {
							return "<div ext:qtip='" + v
									+ "'>&nbsp;&nbsp;&nbsp;&nbsp;" + v
									+ "</div>";
						}
					},
					{
						header : '正片',
						dataIndex : 'contentFlag',
						width : 80,
						fixed : true,
						editor : contentFlagCombo,
						renderer : function(v) {
							if (v == 1) {
								return "正片";
							} else if (v == 2) {
								return "预告片";
							} else {
								return "";
							}
						}
					},
					{
						header : '播放序列',
						dataIndex : 'itemOrder',
						width : 60,
						fixed : true,
						sortable : true,
						editor : new Ext.form.NumberField({
							editable : true,
							allowNegative : false,
							allowBlank : false,
							decimalPrecision : 2,
							minValue : 0
						})
					},
					{
						header : '版本',
						dataIndex : 'contentVersion',
						width : 100,
						fixed : true,
						editor : contentVersionCombo
					},
					{
						header : '描述',
						dataIndex : 'itemDescription',
						width : 350,
						fixed : true,
						editor : new Ext.form.TextField({
							editable : true,
							allowNegative : false,
							allowBlank : true,
							decimalPrecision : 2,
							minValue : 0
						}),
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '操作',
						width : 50,
						dataIndex : 'id',
						renderer : function(v) {
							return "<a style='color:blue;text-decoration:underline;cursor:pointer' onClick=removeFromItemGrid('"
									+ v
									+ "')>"
									+ TXT_Common_Remove_Out
									+ "</a>";
						}
					} ]);

	itemDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			totalProperty : 'totalCount',
			id : 'itemId',
			fields : [ {
				name : 'itemName'
			}, {
				name : 'contentFlag'
			}, {
				name : 'itemOrder'
			}, {
				name : 'contentVersion'
			}, {
				name : 'itemDescription'
			}, {
				name : 'id'
			} ]
		})
	});

	itemDs.baseParams = {
		'cmd' : 'infoHeaderCommand',
		'action' : 'getInfoHeaderItemByHeaderId'
	};

	if (!isNew) {
		loadItemGrid(headerId);
	}

	itemGrid = new Ext.grid.EditorGridPanel({
		id : "infoHeaderItemGrid",
		border : false,
		region : 'center',
		width : 955,
		height : 260,
		ds : itemDs,
		cm : itemCm,
		sm : itemSm,
		stripeRows : true,
		title : "共有 0 条节目",
		loadMask : {
			msg : 'searching...'
		},
		viewConfig : {
			forceFit : true
		}
	});

	itemDs.on('load', function() {
		setItemGridTitle();
	});

	return itemGrid;
}

function loadItemGrid(headerId) {
	// clear itemStatusArray
	itemStatusArray = new Array();

	// load items data
	itemDs.load({
		params : {
			dataSourceKey : BestvSearch.DataSourceKey,
			headerId : headerId,
			flag : Math.random()
		}
	});
}

function getHeaderDetail(headerCode) {
	var url = DISPATCH_URL
			+ "?cmd=infoHeaderCommand&action=getHeaderDetailByCode&code="
			+ headerCode + "&dataSourceKey=" + BestvSearch.DataSourceKey
			+ "&ulf=y&flag=" + Math.random();

	var conn = Ext.lib.Ajax.getConnectionObject().conn;
	conn.open("GET", url, false);
	conn.send(null);
	if (conn.responseText == '[null]') {
		Ext.Msg.alert(TXT_common_hint, TXT_common_relogin, function() {
			window.location.href = '../eni/common/logout.jsp';
		});
		return null;
	} else if (conn.responseText != '') {
		var header = eval(conn.responseText);
		return header;
	}
}

function removeFromItemGrid(id) {
	var index = 0;
	for (index = 0; index < itemDs.data.length; index++) {
		var record = itemDs.getAt(index);
		var idInRecord = record.get("id");
		if (idInRecord == id) {
			itemDs.remove(record);
			itemStatusArray[itemStatusArray.length] = new ItemStatusRecord({
				type : 'remove',
				record : record
			});
			setItemGridTitle();
			break;
		}
	}
}

function setItemGridTitle() {
	var count = itemDs.data.length;
	itemGrid.setTitle("共有 " + count + "条节目");
}

function addItemToGrid() {
	infoNameField = new Ext.form.TextField({
		fieldLabel : TXT_search_keyword_label,
		id : 'infoNameTextField',
		name : 'infoNameTextField',
		allowBlank : false,
		afterRender : function() {
			infoNameField.getEl().on('keyup', function(e) {
				e.stopEvent();
				if ((e.getKey() == Ext.EventObject.ENTER)) {
					infoSearchButtonClick();
				}
			})
		}
	});

	var infosearchButton = new Ext.Button({
		id : "infosearchButton",
		text : TXT_search_button_text,
		type : "button",
		cls : 'x-toolbar',
		handler : infoSearchButtonClick
	});

	var selectAllBtn = new Ext.Button({
		id : "selectAllBtn",
		text : TXT_vod_select_all,
		type : "button",
		cls : 'x-toolbar',
		handler : selectAll
	});

	var unselectAllBtn = new Ext.Button({
		id : "unselectAllBtn",
		text : TXT_vod_unselect_all,
		type : "button",
		cls : 'x-toolbar',
		handler : unselectAll
	});

	var infoSm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});
	var infoCm = new Ext.grid.ColumnModel(
			[
					{
						header : "<div style='text-align:center;width:100%;'>"
								+ TXT_common_select + "</div>",
						dataIndex : 'id',
						width : 80,
						fixed : true,
						renderer : function(v) {
							var existFlag = existInItemDs(v);
							if (existFlag) {
								return "<div style='text-align:center;'><input type='checkbox' name='infoSelectCheckBox' disabled='true' checked=true value='"
										+ v + "'></input></div>";
							} else {
								return "<div style='text-align:center;'><input type='checkbox' name='infoSelectCheckBox' value='"
										+ v + "'></input></div>";
							}
						}
					}, {
						header : TXT_vod_name,
						dataIndex : 'name',
						width : 200,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					}, {
						header : 'code',
						dataIndex : 'code',
						width : 260
					}, {
						header : TXT_vod_type,
						dataIndex : 'p_type',
						width : 80
					}, {
						header : TXT_Common_Vod_Clarity,
						dataIndex : 'hd',
						width : 80,
						renderer : function(v) {
							if (v == 0) {
								return '标清'
							} else if (v == 1) {
								return '高清'
							} else {
								return '其他'
							}
						}
					}, {
						header : TXT_common_description,
						dataIndex : 'description',
						width : 450,
						renderer : function(v) {
							return "<div ext:qtip=" + v + ">" + v + "</div>";
						}
					} ]);

	infoDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			totalProperty : 'totalCount',
			id : 'id',
			fields : [ {
				name : 'id'
			}, {
				name : 'name'
			}, {
				name : 'p_type'
			}, {
				name : 'code'
			}, {
				name : 'hd'
			}, {
				name : 'description'
			}, {
				name : 'contentFlag'
			}, {
				name : 'contentVersion'
			} ]
		})
	});

	infoDs.baseParams = {
		'cmd' : 'info',
		'action' : 'getInfosLikeName'
	};

	var infoGrid = new Ext.grid.GridPanel(
			{
				id : 'infoGrid',
				border : false,
				region : 'center',
				width : 1000,
				height : 510,
				tbar : [ selectAllBtn, unselectAllBtn, '->',
						TXT_search_keyword_label + ":", infoNameField,
						infosearchButton ],
				ds : infoDs,
				cm : infoCm,
				sm : infoSm,
				stripeRows : true,
				loadMask : {
					msg : 'searching...'
				},
				viewConfig : {
					forceFit : true
				},
				listeners : {
					'keydown' : function(e) {
						e.stopEvent();
						PagingToolbar_KeyEventForInfoGrid(Ext
								.getCmp('infoGridPagingToolbar'), e);
					}
				},
				bbar : new Ext.PagingToolbar(
						{
							id : 'infoGridPagingToolbar',
							pageSize : infoPageSize,
							height : 20,
							store : infoDs,
							displayInfo : true,
							displayMsg : TXT_common_paging,
							emptyMsg : TXT_common_no,
							onPagingKeydown : function(e) {
								PagingToolbar_KeyEventForInfoGrid(this, e);
							},
							onClick : function(which) {
								switch (which) {
								case 'prev':
									infoStartIndex = infoStartIndex
											- infoPageSize;
									break;
								case 'first':
									infoStartIndex = 0;
									break;
								case 'next':
									infoStartIndex = infoStartIndex
											+ infoPageSize;
									break;
								case 'last':
									infoStartIndex = ((this.store
											.getTotalCount() / infoPageSize) | 0)
											* infoPageSize;
									break;
								default:
								}

								// Gets data
								loadInfoData();
							}
						})
			});

	var window = null;
	window = new Ext.Window(
			{
				width : 1020,
				autoHeight : true,
				height : 400,
				items : infoGrid,
				plain : true,
				title : TXT_Common_Vod_List,
				autoScroll : true,
				buttons : [
						{
							text : TXT_common_close,
							handler : function() {
								if (window != null) {
									window.close();
								}
							}
						},
						{
							text : '添加至剧头列表',
							handler : function() {
								var checkBoxs = document
										.getElementsByName("infoSelectCheckBox");
								var hasSelected = false;
								for ( var i = 0; i < checkBoxs.length; i++) {
									if (checkBoxs[i].checked == true) {
										if (checkBoxs[i].disabled == false) {
											hasSelected = true;
											var id = checkBoxs[i].value;
											var record = getRecordFromInfoDs(id);
											if (record != null) {
												var itemRecord = new ItemRecord(
														{
															id : id,
															itemName : record
																	.get("name"),
															contentFlag : record
																	.get("contentFlag"),
															itemOrder : '',
															contentVersion : record
																	.get("contentVersion"),
															itemDescription : ''

														});
												itemGrid.stopEditing();
												itemDs.add(itemRecord);
												itemStatusArray[itemStatusArray.length] = new ItemStatusRecord(
														{
															type : 'add',
															record : itemRecord
														});
											}
											checkBoxs[i].disabled = true;
											setItemGridTitle();
											Ext.Msg.alert(TXT_common_hint,
													'添加成功！');
										}
									}
								}

								if (!hasSelected) {
									Ext.Msg.alert(TXT_common_hint, '请至少选中一行。');
									return;
								}
							}
						} ]
			});

	window.setPosition(100, 10);
	window.show();
}

function PagingToolbar_KeyEventForInfoGrid(thisPagingToolbar, e) {
	if ((e.getKey() == Ext.EventObject.ENTER)) {
		var currPage = thisPagingToolbar.readPage();
		var totalPage = thisPagingToolbar.getPageData().pages;

		if (currPage > totalPage) {
			Ext.Msg.alert(TXT_common_hint, TXT_Common_Correct_PageNum);
			return;
		} else {
			if (currPage <= 0) {
				infoStartIndex = 0;
			} else {
				infoStartIndex = (currPage - 1) * infoPageSize;
			}

			// Gets data
			loadInfoData();
		}
	}
	return;
}

function loadInfoData() {
	var name = infoNameField.getValue();
	if (name == null || name == '') {
		Ext.Msg.alert(TXT_common_hint, '请输入搜索关键字');
		return;
	}

	infoDs
			.load({
				params : {
					name : name,
					start : infoStartIndex,
					limit : infoPageSize,
					dataSourceKey : BestvSearch.DataSourceKey
				},
				callback : function(r, options, success) {
					if (r.length == 0 && !success) {
						if (infoDs.reader.responseText == '[null]') {
							Ext.Msg
									.alert(
											TXT_common_hint,
											TXT_common_relogin,
											function() {
												window.location.href = '../eni/common/logout.jsp';
											});
							return;
						} else {
							Ext.Msg.alert(TXT_common_hint,
									TXT_SITE_CONFIGURATION_CHECK);
							return;
						}
					}
				}
			});
}

function infoSearchButtonClick() {
	infoStartIndex = 0;

	loadInfoData()
}

function existInItemDs(info_id) {
	var length = itemDs.data.length;
	for ( var i = 0; i < length; i++) {
		var record = itemDs.getAt(i);
		var idInRecord = record.get("id");
		if (idInRecord == info_id) {
			return true;
		}
	}
	return false;
}

function getRecordFromInfoDs(info_id) {
	var length = infoDs.data.length;
	for ( var i = 0; i < length; i++) {
		var record = infoDs.getAt(i);
		var idInRecord = record.get("id");
		if (idInRecord == info_id) {
			return record;
		}
	}
	return null;
}

function selectAll() {
	var checkBoxs = document.getElementsByName("infoSelectCheckBox");
	for ( var i = 0; i < checkBoxs.length; i++) {
		if (checkBoxs[i].disabled == false) {
			checkBoxs[i].checked = true;
		}
	}
}

function unselectAll() {
	var checkBoxs = document.getElementsByName("infoSelectCheckBox");
	for ( var i = 0; i < checkBoxs.length; i++) {
		if (checkBoxs[i].disabled == false) {
			checkBoxs[i].checked = false;
		}
	}
}

// Save info header and infoHeader items
function saveAll(isNew, headerId, headerName, headerAliasName, headerTypeCombo,
		headerGenre, headerTags, headerWriters, headerActors, headerRegion,
		headerReleased, headerVodType, headerDescription, headerClarityCombo,
		headerIsChargeCombo, headerLanguage, headerCategory, headerCrowd,
		headerKeyword) {

	if (itemGrid.getStore().data.length == 0) {
		Ext.Msg.alert(TXT_common_hint, '剧头至少包含一个剧集');
		return;
	}

	var modifiedRecords = itemGrid.getStore().modified;
	var addRemoveRecords = itemStatusArray;

	var removeJSON = "[";
	var saveOrUpdateJSON = "[";
	for ( var i = 0; i < addRemoveRecords.length; i++) {
		var addRemoveRecord = addRemoveRecords[i];
		var type = addRemoveRecord.get("type");
		var record = addRemoveRecord.get("record");
		var info_id = record.get("id");
		if (type == 'add') {
			if (existInAddRemoveRecords(addRemoveRecords, i + 1, info_id)
					|| existInModifiedRecords(modifiedRecords, 0, info_id)) {
				continue;
			} else {
				saveOrUpdateJSON += "{info_header_id:" + headerId + ",info_id:"
						+ record.data.id + ",info_order:"
						+ record.data.itemOrder + ",description:\""
						+ record.data.itemDescription + "\",contentVersion:\""
						+ record.data.contentVersion + "\",contentFlag:"
						+ record.data.contentFlag + "},";
			}
			if (headerTypeValue == 'movie') {
				if (record.data.contentVersion == null
						|| record.data.contentVersion == '') {
					Ext.Msg.alert(TXT_common_hint, '请设置所有电影节目的版本');
					return;
				}
			}

			if (record.data.itemOrder == null || record.data.itemOrder == '') {
				Ext.Msg.alert(TXT_common_hint, '请设置所有节目的播放序列');
				return;
			}
		} else {
			if (!isNew) {
				// type equals to remove
				if (existInAddRemoveRecords(addRemoveRecords, i + 1, info_id)
						|| existInModifiedRecords(modifiedRecords, 0, info_id)) {
					continue;
				} else {
					removeJSON += "{info_header_id:" + headerId + ",info_id:"
							+ info_id + "},";
				}
			}
		}
	}

	var headerTypeValue = headerTypeCombo.getValue();
	for ( var j = 0; j < modifiedRecords.length; j++) {
		var record = modifiedRecords[j];
		saveOrUpdateJSON += "{info_header_id:" + headerId + ",info_id:"
				+ record.data.id + ",info_order:" + record.data.itemOrder
				+ ",description:\"" + record.data.itemDescription
				+ "\",contentVersion:\"" + record.data.contentVersion
				+ "\",contentFlag:" + record.data.contentFlag + "},";

		if (headerTypeValue == 'movie') {
			if (record.data.contentVersion == null
					|| record.data.contentVersion == '') {
				Ext.Msg.alert(TXT_common_hint, '请设置所有电影节目的版本');
				return;
			}
		}

		if (record.data.itemOrder == null || record.data.itemOrder == '') {
			Ext.Msg.alert(TXT_common_hint, '请设置所有节目的播放序列');
			return;
		}
	}

	if (removeJSON.endWith(",")) {
		removeJSON = removeJSON.substr(0, removeJSON.length - 1) + "]"
	} else {
		removeJSON += "]"
	}
	if (saveOrUpdateJSON.endWith(",")) {
		saveOrUpdateJSON = saveOrUpdateJSON.substr(0,
				saveOrUpdateJSON.length - 1)
				+ "]"
	} else {
		saveOrUpdateJSON += "]"
	}

	if (headerName.getValue() == null || headerName.getValue() == '') {
		Ext.Msg.alert(TXT_common_hint, '请指定节目名称');
		return;
	}

	var headerJSON = "{id:\"" + headerId + "\",name:\"" + headerName.getValue()
			+ "\",alias_name:\"" + headerAliasName.getValue()
			+ "\",headerType:\"" + headerTypeCombo.getValue() + "\",genre:\""
			+ headerGenre.getValue() + "\",tags:\"" + headerTags.getValue()
			+ "\",writers:\"" + headerWriters.getValue() + "\",actors:\""
			+ headerActors.getValue() + "\",region:\""
			+ headerRegion.getValue() + "\",releasedStr:\""
			+ headerReleased.getValue().format("Y-m-d") + "\",p_type:\""
			+ headerVodType.getValue() + "\",description:\""
			+ headerDescription.getValue() + "\",clarity_flag:\""
			+ headerClarityCombo.getValue() + "\",isCharge:\""
			+ headerIsChargeCombo.getValue() + "\",language:\""
			+ headerLanguage.getValue() + "\",category:\""
			+ headerCategory.getValue() + "\",content_crowd:\""
			+ headerCrowd.getValue() + "\",keywords:\""
			+ headerKeyword.getValue() + "\"}";

	var url = DISPATCH_URL
			+ "?cmd=infoHeaderCommand&action=createOrEditInfoHeader&dataSourceKey="
			+ BestvSearch.DataSourceKey + "&ulf=y&isNew=" + isNew + "&header="
			+ headerJSON + "&removeItems=" + removeJSON + "&saveOrUpdateItems="
			+ saveOrUpdateJSON;

	var conn = Ext.lib.Ajax.getConnectionObject().conn;
	conn.open("POST", url, false);
	conn.send(null);
	if (conn.responseText == '[null]') {
		Ext.Msg.alert(TXT_common_hint, TXT_common_relogin, function() {
			window.location.href = '../eni/common/logout.jsp';
		});
		return null;
	} else if (conn.responseText != '') {
		if (conn.responseText == 'success') {
			Ext.Msg.alert(TXT_common_hint, TXT_Common_Operation_Success);
			loadData();
		} else if (conn.responseText == 'exist') {
			Ext.Msg.alert(TXT_common_hint, '该节目头已存在，请查找并对其修改');
			searchKeyWordField.setValue(headerName.getValue());
		} else {
			Ext.Msg.alert(TXT_common_hint, TXT_common_access_fail);
		}
	}
}

function existInAddRemoveRecords(addRemoveRecords, startIndex, id) {
	for ( var i = startIndex; i < addRemoveRecords.length; i++) {
		var addRemoveRecord = addRemoveRecords[i];
		var record = addRemoveRecord.get("record");
		var info_id = record.get("id");
		if (id == info_id) {
			return true;
		}
	}
	return false;
}

function existInModifiedRecords(modifiedRecords, startIndex, id) {
	for ( var i = startIndex; i < modifiedRecords.length; i++) {
		var modifiedRecord = modifiedRecords[i];
		var info_id = modifiedRecord.data.id;
		if (id == info_id) {
			return true;
		}
	}
	return false;
}